package com.xgsm.fastdfsdemo.Service;

import com.github.tobato.fastdfs.service.FastFileStorageClient;
import com.xgsm.fastdfsdemo.Bean.FastDfsFile;
import com.xgsm.fastdfsdemo.Bean.TimeMillUntil;
import com.xgsm.fastdfsdemo.UUIDUtil;
import com.xgsm.fastdfsdemo.mapper.FastDfsFileMapper;
import org.apache.commons.io.FilenameUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

/**
 * @ClaseName: FastdfsServiceImpl$
 * @Description:
 * @Author: wuhs
 * @Date: 2023/5/12$ 11:46$
 * @param: $
 * @return: $
 */
@Service
public class FastdfsServiceImpl implements FastDfsSercive {
    private UUIDUtil util;
    @Resource
    private FastFileStorageClient fastFileStorageClient;
    @Autowired
    private FastDfsFileMapper fastDfsFileMapper;
    @Autowired
    private RedisTemplate<String, String> redisTemplate;

    private TimeMillUntil millUntil = new TimeMillUntil();
    //fastDFS storage存储节点路径  xxxxxx：服务器ip
    private final String FASTDFSSERVERIMAGE = "http://124.221.94.214:8888/";
    private final String COMMONPATH = "/fastdfs/";

    @Override
    @Transactional
    public Map<String, String> insertAndUpload(MultipartFile file) {
        String proName = file.getOriginalFilename();
        String substring1 = proName.substring(0, proName.indexOf("."));
        //上传文件并获取在服务器中存储的位置
        String storePath = null;
        HashMap<String, String> result = new HashMap<>();
        try {
            storePath = fastFileStorageClient.uploadFile(file.getInputStream(), file.getSize(), FilenameUtils.getExtension(file.getOriginalFilename()), null).getFullPath();
            int s = millUntil.getCurrentTimeMill();
            FastDfsFile fastDfsFile = new FastDfsFile(s, substring1, storePath, 0);
            //缓存
            redisTemplate.opsForValue().set(COMMONPATH + substring1, storePath + ">" + s);
            //数据持久化
            int insert = fastDfsFileMapper.insert(fastDfsFile);
            //这里msg返回的是上传后的图片存储位置getFullPath()获取文件位置
            if (insert != 0) {
                result.put("msg", FASTDFSSERVERIMAGE + storePath);
            } else {
                result.put("msg", "数据持久化失败");
            }
        } catch (IOException e) {
            e.printStackTrace();
        }

        return result;


    }
}
